package com.baijiayun.live.ui.speakpanel

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import com.baijiayun.live.ui.R
import com.baijiayun.live.ui.base.getViewModel
import com.baijiayun.live.ui.pptpanel.MyPadPPTView
import com.baijiayun.live.ui.speakerlist.item.Playable
import com.baijiayun.live.ui.speakerlist.item.Switchable
import com.baijiayun.live.ui.speakerlist.item.SwitchableStatus
import com.baijiayun.livecore.context.LPConstants
import com.baijiayun.livecore.models.LPUserModel
import com.baijiayun.livecore.models.imodels.IUserModel
import com.baijiayun.livecore.utils.LPRxUtils
import com.baijiayun.livecore.wrapper.LPRecorder
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.bjy_layout_item_video.view.*
import java.util.concurrent.TimeUnit

/**
 * 1v1 学生容器(自动上台)
 */
class SingleSpeakFragment : SpeakFragment() {
    private val speakViewModel by lazy {
        getViewModel { SpeakViewModel(routerViewModel) }
    }

    private var timeDisposable: Disposable? = null

    private val placeholderItem by lazy {
        LayoutInflater.from(context).inflate(R.layout.bjy_layout_item_video, container, false) as ViewGroup
    }

    private val navigateToMainObserver by lazy {
        Observer<Boolean> {
            if (it == true) {
                initSuccess()
                speakViewModel.subscribe()
            }
        }
    }

    override fun getLayoutId(): Int = R.layout.fragment_pad_main_video

    override fun observeActions() {
        super.observeActions()
        routerViewModel.actionNavigateToMain.observeForever(navigateToMainObserver)
    }

    override fun init(view: View) {
        container = view as ViewGroup
    }

    private fun initSuccess() {
        container.removeAllViews()
        container.addView(placeholderItem)
        showRemoteStatus(false, LPUserModel())
        speakViewModel.singleSpeakerChange.observe(this, Observer {
            it?.let {
                showRemoteStatus(!it.first, it.second)
            }
        })

        routerViewModel.isClassStarted.observe(this, Observer {
            if (it == true) {
                enableAutoSpeak()
            }
        })
    }

    override fun showClassEnd() {
        super.showClassEnd()
        showRemoteStatus(speakViewModel.singleSpeakerChange.value?.first != true,
                speakViewModel.singleSpeakerChange.value?.second)
    }

    private fun isAutoSpeak() = routerViewModel.liveRoom.roomType == LPConstants.LPRoomType.Single ||
            routerViewModel.liveRoom.roomType == LPConstants.LPRoomType.SmallGroup || routerViewModel.liveRoom.roomType == LPConstants.LPRoomType.OneOnOne

    /**
     * 一对一、小班课上课学生自动举手上麦，试听不上麦
     * 申请权限时，2种权限要合并一起申请，单独申请需要连续申请,
     * 即在onRequestPermissionsResult回调里面再申请另一个
     */
    private fun enableAutoSpeak() = with(routerViewModel) {
        if (isAutoSpeak() && liveRoom.currentUser.type == LPConstants.LPUserType.Student && !liveRoom.isAudition) {
            liveRoom.getRecorder<LPRecorder>().publish()
            if (liveRoom.autoOpenCameraStatus) {
                if (checkCameraAndMicPermission()) {
                    if (!liveRoom.getRecorder<LPRecorder>().isAudioAttached) {
                        attachLocalAudio()
                    }
                    if (liveRoom.autoOpenCameraStatus) {
                        timeDisposable = Observable.timer(500, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread())
                                .subscribe { attachLocalVideo() }
                    }
                }
            } else {
                if (!liveRoom.getRecorder<LPRecorder>().isAudioAttached) {
                    attachLocalAudio()
                }
            }
        }
    }

    private fun showRemoteStatus(isLeave: Boolean, user: IUserModel?) {
        if (isLeave) {
            placeholderItem.item_status_placeholder_iv.setImageResource(R.drawable.base_ic_video_leave)
            placeholderItem.item_status_placeholder_tv.text = getString(R.string.pad_leave_room_single_speaker)
        } else {
            placeholderItem.item_status_placeholder_iv.setImageResource(R.drawable.base_ic_video_leave)
            placeholderItem.item_status_placeholder_tv.text = getString(R.string.pad_not_onseat)
        }
        placeholderItem.item_local_speaker_name.text = user?.name ?: ""
        placeholderItem.item_local_speaker_name.visibility = View.VISIBLE
        placeholderItem.visibility = View.VISIBLE
        if (isLeave) {
            //学生离开教室把原来在学生位置的ppt移到全屏位置
            val myPadPPTView = routerViewModel.pptViewData.value as MyPadPPTView
            if (myPadPPTView.pptStatus == SwitchableStatus.SpeakList) {
                myPadPPTView.switchPPTVideoWithoutSync(true)
            }
        }
        container.removeAllViews()
        container.addView(placeholderItem)
    }

    override fun forceKeepAlive() = true

    override fun addView(child: View, index: Int, switchable: Switchable) {
        if (switchable is Playable && switchable.user.type != LPConstants.LPUserType.Student) {
            return
        }
        container.removeAllViews()
        container.addView(child)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        LPRxUtils.dispose(timeDisposable)
        routerViewModel.actionNavigateToMain.removeObserver(navigateToMainObserver)
        (view as ViewGroup).removeAllViews()
    }

    companion object {
        fun newInstance() = SingleSpeakFragment()
    }

}